/**
 * 聊天窗口服务
 * 管理聊天窗口之间的通信和数据同步
 */

const { ipcMain, BrowserWindow } = require('electron');
const { logger } = require('ee-core/log');

/**
 * 聊天窗口服务类
 * 处理多窗口聊天的数据同步
 */
class ChatWindowService {
  constructor() {
    // 窗口ID与聊天ID的映射
    this.windowMap = new Map();
    this.chatIdMap = new Map();
    
    // 注册IPC处理程序
    this.registerIpcHandlers();
  }

  /**
   * 创建服务
   */
  create() {
    logger.info('[chat window service] created');
  }

  /**
   * 注册IPC处理程序
   */
  registerIpcHandlers() {
    // 初始化聊天窗口数据
    ipcMain.on('init-chat-window', (event, { wcid, chatData }) => {
      try {
        logger.info('[chat window service] init-chat-window for wcid:', wcid);
        
        const win = BrowserWindow.fromId(wcid);
        if (!win) {
          event.reply('init-chat-window-reply', { success: false, error: 'Window not found' });
          return;
        }

        // 记录窗口ID与聊天ID的映射关系
        this.windowMap.set(wcid, chatData.targetId);
        this.chatIdMap.set(chatData.targetId, wcid);
        
        // 发送初始化数据到窗口
        win.webContents.send('init-chat-data', { chatData });
        
        // 监听窗口关闭事件
        win.on('closed', () => {
          this.handleWindowClosed(wcid, chatData.targetId);
        });
        
        event.reply('init-chat-window-reply', { success: true });
      } catch (error) {
        logger.error('[chat window service] init-chat-window error:', error);
        event.reply('init-chat-window-reply', { success: false, error: error.message });
      }
    });

    // 同步聊天数据
    ipcMain.on('sync-chat-data', (event, { chatId, chatData }) => {
      try {
        logger.info('[chat window service] sync-chat-data for chatId:', chatId);
        
        // 获取对应的窗口
        const wcid = this.chatIdMap.get(chatId);
        const win = wcid ? BrowserWindow.fromId(wcid) : null;
        
        if (win && !win.isDestroyed() && win.webContents) {
          win.webContents.send('chat-data-updated', { chatId, chatData });
          event.reply('sync-chat-data-reply', { success: true });
        } else {
          event.reply('sync-chat-data-reply', { success: false, error: 'Window not found or not available' });
        }
      } catch (error) {
        logger.error('[chat window service] sync-chat-data error:', error);
        event.reply('sync-chat-data-reply', { success: false, error: error.message });
      }
    });

    // 广播消息到其他窗口
    ipcMain.on('broadcast-message', async (event, data) => {
      try {
        const windows = BrowserWindow.getAllWindows();
        const senderWin = BrowserWindow.fromWebContents(event.sender);

        for (const win of windows) {
          try {
            // 跳过发送窗口和已销毁的窗口
            if (win === senderWin || win.isDestroyed()) {
              continue;
            }

            // 发送消息到窗口
            await win.webContents.send('message-received', {
              chatId: data.chatId,
              mutation: data.mutation,
              chatData: data.chatData
            });

            console.log('Message sent to window:', win.id);
          } catch (error) {
            console.error('Error sending message to window:', win.id, error);
          }
        }
      } catch (error) {
        console.error('Error broadcasting message:', error);
      }
    });

    // 处理新窗口发来的更新请求
    ipcMain.on('update-main-window', (event, data) => {
      try {
        logger.info('[chat window service] updating main window');
        
        // 获取主窗口
        const mainWindow = BrowserWindow.getAllWindows().find(win => 
          !this.windowMap.has(win.id) && 
          !win.isDestroyed() && 
          win.webContents && 
          win.webContents.getURL().includes('index.html')
        );
        
        if (!mainWindow) {
          event.reply('update-main-window-reply', { success: false, error: '主窗口未找到' });
          return;
        }

        mainWindow.webContents.send('main-window-update', data);
        logger.info('[chat window service] Message sent to main window');
        event.reply('update-main-window-reply', { success: true });
      } catch (error) {
        logger.error('[chat window service] update-main-window error:', error);
        event.reply('update-main-window-reply', { success: false, error: error.message });
      }
    });
  }

  /**
   * 处理窗口关闭事件
   */
  handleWindowClosed(wcid, chatId) {
    try {
      logger.info('[chat window service] window closed, wcid:', wcid, 'chatId:', chatId);
      
      // 从映射中移除
      this.windowMap.delete(wcid);
      this.chatIdMap.delete(chatId);
      
      // 通知主窗口窗口已关闭
      const mainWindow = BrowserWindow.getAllWindows().find(win => 
        !this.windowMap.has(win.id) && 
        !win.isDestroyed() && 
        win.webContents && 
        win.webContents.getURL().includes('index.html')
      );
      
      if (mainWindow) {
        mainWindow.webContents.send('chat-window-closed', chatId);
      }
    } catch (error) {
      logger.error('[chat window service] handleWindowClosed error:', error);
    }
  }
}

const chatWindowService = new ChatWindowService();

exports.chatWindowService = chatWindowService; 